package com.platform.feign.spring.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * @author hgx
 * feign json解码器
 * 重写了
 */
@Component
public class PlatformFeignDecoder implements Decoder {

    @Resource
    @Qualifier("platformFeignFastJsonConfig")
    private FastJsonConfig platformFastJsonConfig;


//    public PlatformJacksonDecoder() {
//        this(Collections.<Module>emptyList());
//    }

//    public PlatformJacksonDecoder(Iterable<Module> modules) {
//        this(new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
//                .registerModules(modules));
//    }

//    public PlatformJacksonDecoder(ObjectMapper mapper) {
//        this.mapper = mapper;
//    }

    @Override
    public Object decode(Response response, Type type) throws IOException {
        if (response.status() == 404) return Util.emptyValueOf(type);
        if (response.body() == null) return null;
        InputStream inputStream = response.body().asInputStream();
        if (!inputStream.markSupported()) {
            inputStream = new BufferedInputStream(inputStream, 1);
        }
        try {
            // Read the first byte to see if we have any data
            inputStream.mark(1);
            if (inputStream.read() == -1) {
                return null; // Eagerly returning null avoids "No content to map due to end-of-input"
            }
            inputStream.reset();

            JSONObject jsonObject = JSON.parseObject(response.body().asInputStream(), platformFastJsonConfig.getCharset(), JSONObject.class, platformFastJsonConfig.getFeatures());

            return jsonObject.getObject("data", type);


//            Reader reader = response.body().asReader(StandardCharsets.UTF_8);
//            if (!reader.markSupported()) {
//                reader = new BufferedReader(reader, 1);
//            }
//            try {
//                // Read the first byte to see if we have any data
//                reader.mark(1);
//                if (reader.read() == -1) {
//                    return null; // Eagerly returning null avoids "No content to map due to end-of-input"
//                }
//                reader.reset();
//
//                //解析出公共封装下的数据，此处可以处理公共状态码等
//                JsonResult jsonResult = mapper.readValue(reader, JsonResult.class);
//                return mapper.convertValue(jsonResult.getData(), mapper.constructType(type));


//            BufferedReader bufferedReader = new BufferedReader(reader);
//
//            String line;
//            final StringBuilder builder = new StringBuilder(2048);
//            while ((line = bufferedReader.readLine()) != null) {
//                builder.append(line);
//            }
//            bufferedReader.close();
//
//            JSONObject jsonObject = JSON.parseObject(builder.toString());
//            return jsonObject.getObject("data", type);
        } catch (RuntimeJsonMappingException e) {
            if (e.getCause() != null && e.getCause() instanceof IOException) {
                throw (IOException) e.getCause();
            }
            throw e;
        }
    }
}
